package com.runmi.webchat.aftersale.web.set.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.runmi.webchat.aftersale.common.page.PageModel;
import com.runmi.webchat.aftersale.common.result.Result;
import com.runmi.webchat.aftersale.common.result.ResultFactory;
import com.runmi.webchat.aftersale.common.utils.StringUtil;
import com.runmi.webchat.aftersale.dbcore.entity.AdminMenu;
import com.runmi.webchat.aftersale.dbcore.entity.Role;
import com.runmi.webchat.aftersale.dbcore.entity.RoleMenu;
import com.runmi.webchat.aftersale.dbcore.entity.User;
import com.runmi.webchat.aftersale.dbcore.mapper.AdminMenuMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.RoleMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.RoleMenuMapper;
import com.runmi.webchat.aftersale.dbcore.mapper.UserMapper;
import com.runmi.webchat.aftersale.util.Constants;
import com.runmi.webchat.aftersale.web.base.BaseService;
import com.runmi.webchat.aftersale.web.set.model.RoleConfig;
import com.runmi.webchat.aftersale.web.set.model.RoleConfigItem;
import com.runmi.webchat.aftersale.web.set.model.RoleConfigSave;
import com.runmi.webchat.aftersale.web.set.model.RoleEdit;
import com.runmi.webchat.aftersale.web.set.model.RoleIndex;

import io.swagger.annotations.ApiParam;

@Service
public class RoleService  extends BaseService{


	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private AdminMenuMapper adminMenuMapper;
	
	@Autowired
	private RoleMenuMapper roleMenuMapper;

	
	/**
	 * 角色列表查询
	 * @param roleId
	 * @param roleName
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	public void index(RoleIndex model){
		try{
		
			PageHelper.startPage(model.getCpage(),model.getPageSize());
			List<Role> items=roleMapper.getRoleSeach(
					model.getRoleId(),
					model.getRoleName());			
			PageInfo<Role> pageInfo = new PageInfo<Role>(items);
			model.setTotalCount((int)pageInfo.getTotal());
			model.setItems(items);
					
		}catch(Exception ex){
			ex.printStackTrace();
			//result.setReturnMessage(ex.getMessage());
		}
		
	}
	/**
	 * 获取角色列表
	 * @return
	 */
	public Result getAllRoles(){
	    Result result= ResultFactory.getResultFail();
		try{			
			List<Role> items=roleMapper.getAllRoleInfo();
			result=ResultFactory.getResultListSuccess(items);
					
		}catch(Exception ex){
			ex.printStackTrace();
			result.setReturnMessage(ex.getMessage());
		}
		return result;
		
	}
	public Result getRoleById(Integer jobId){
		Result result=null;
		try{
			Role scmRole= roleMapper.selectByPrimaryKey(jobId);
			if(null!=scmRole){
				result=ResultFactory.getResultSuccess(scmRole);
			}else{
				result=ResultFactory.getResultFail("未查询到角色信息");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			result=ResultFactory.getResultFail();
		}
		return result;
	}
			
	public void edit(RoleEdit model){
		Role role=null;
				if(null!=model.getRoleId()){		
					role= roleMapper.selectByPrimaryKey(model.getRoleId());
				}
				role=role==null?new Role():role;
				model.setRole(role);
				
	}
		
	public Map<String,String> saveRole(User user,Integer roleId,String roleName,String remark){
			Map<String,String> result=new HashMap<String,String>();
			if(null!=roleId){
				Role role= roleMapper.selectByPrimaryKey(roleId);
				if(null!=role){				
					if(StringUtil.isBlank(roleName)){					
						result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
						result.put(Constants.RETURN_MESSAGE_KEY, "请输入角色名称");		
						return result;
						
					}							
					Role record=new Role();
					record.setId(roleId);
					record.setRoleName(roleName);
					record.setRemark(remark);
					record.setUpdateTime(new Date());
					record.setUpdateUserId(user.getId());
					record.setUpdateUserName(user.getRealName());
					roleMapper.updateByPrimaryKeySelective(record);
				}else{
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "未查询到角色");					
					return result;
				}
			}else{
				
				Role record=new Role();
				record.setId(roleId);
				record.setRoleName(roleName);
				record.setRemark(remark);
				record.setCreateUserId(user.getId());
				record.setCreateUserName(user.getRealName());
				record.setDelFlag((byte)0);
				record.setStatus((byte)1);
				record.setCreateTime(new Date());
				roleMapper.insertSelective(record);
			}
			result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_SUCCESS);
			result.put(Constants.RETURN_MESSAGE_KEY, "success");	
			return result;
		}
		
		
		
	public Map<String,String> delRole(User user, Integer roleId){
			Map<String,String> result=new HashMap<String,String>();
			try{
				this.log.info("用户" + user.getRealName() + "  del role:" + roleId );
				if(roleId==null){
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "数据异常");					
					return result;
				}
				Role model= roleMapper.selectByPrimaryKey(roleId);
				if(null==model){
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "未查询到角色");					
					return result;
				}
				
				Role record=new Role();
					record.setId(model.getId());
					record.setUpdateTime(new Date());
					record.setDelFlag((byte)1);	
					record.setUpdateUserId(user.getId());
					record.setUpdateUserName(user.getRealName());
					roleMapper.updateByPrimaryKeySelective(record);
				
				
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_SUCCESS);
				result.put(Constants.RETURN_MESSAGE_KEY, "success");		
				
				
			}catch(Exception ex){
				ex.printStackTrace();
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
				result.put(Constants.RETURN_MESSAGE_KEY, ex.getMessage());	
			}
			return result;
		}
		
		public void config(User user,RoleConfig model){
			//Result result=null;
			try{
						
				Role role= roleMapper.selectByPrimaryKey(model.getRoleId());
				model.setRole(role);
				AdminMenu record=new AdminMenu();
				record.setStatus((byte)1);
				record.setDelFlag((byte)0);
				List<AdminMenu> allmenus= adminMenuMapper.select(record);
			
				
				List<AdminMenu> mymenus= adminMenuMapper.getUserMenuByRoleId(model.getRoleId());
				List<RoleConfigItem> items=new ArrayList<RoleConfigItem>();
				List<AdminMenu> menu1=getAdminMenu(allmenus,0,mymenus);
				for(int i=0;i<menu1.size();i++){
					AdminMenu menuAdmin=menu1.get(i);	
					 	List<AdminMenu> menu2=getAdminMenu(allmenus,menuAdmin.getId(),mymenus);			 	
					 	RoleConfigItem menu=new RoleConfigItem();			 	
						menu.setMenuId1(menuAdmin.getId());
						menu.setMenuId1Name(menuAdmin.getMenuName());
						menu.setSelect1(menuAdmin.getStatus());
						if(null!=menu2 && menu2.size()>0){
							AdminMenu menu21=menu2.get(0);
							menu.setMenuId2(menu21.getId());
							menu.setMenuId2Name(menu21.getMenuName());
							menu.setSelect2(menu21.getStatus());
							menu.setParentId(menuAdmin.getId());
							items.add(menu);
							for(int j=1;j<menu2.size();j++){
								AdminMenu menu22=menu2.get(j);
								
								RoleConfigItem menu221=new RoleConfigItem();			 	
								menu221.setMenuId2(menu22.getId());
								menu221.setMenuId2Name(menu22.getMenuName());
								menu221.setSelect2(menu22.getStatus());
								menu221.setParentId(menuAdmin.getId());
								
								items.add(menu221);
							}
						}else{
							
							items.add(menu);
						}				 	
				}
				model.setItems(items);
				//result=ResultFactory.getResultListSuccess(items);
			}catch(Exception ex){
				ex.printStackTrace();
				//result=ResultFactory.getResultFail();
			}
			//return result;
			
//			
		//	return model;
		}
		private Byte checkMenuIsSelect(List<AdminMenu> mymenus,Integer menuId){
			Byte result=(byte)0;
			for(AdminMenu menu:mymenus){
				if(menu.getId().equals(menuId)){
					result=(byte)1;
					break;
				}
			}
			return result;
		}
		private List<AdminMenu> getAdminMenu(List<AdminMenu> menus,Integer parentId,List<AdminMenu> mymenus){
			List<AdminMenu> result=new ArrayList<AdminMenu>();
			for(int i=0;i<menus.size();i++){
				AdminMenu menu=menus.get(i);//administrator   						
					if(menu.getParentId()==parentId){
						Byte select= checkMenuIsSelect(mymenus,menu.getId());
						menu.setStatus(select);
						result.add(menu);
				}
				
			}
			result.sort((h1,h2)->h1.getSort().compareTo(h2.getSort()));
			return result;
		}
		
		@Transactional(rollbackFor={Exception.class, RuntimeException.class})
		public Map<String,String> configSave(User user, RoleConfigSave model){
			Map<String,String> result=new HashMap<String,String>();
			try{
				this.log.info("用户" + user.getRealName() + "  config role:" + model.getRoleId() );
				if(model.getRoleId()==null){
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "数据异常");					
					return result;
				}
		
				Role scmRole= roleMapper.selectByPrimaryKey(model.getRoleId());
				if(null==scmRole){
					result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
					result.put(Constants.RETURN_MESSAGE_KEY, "未查询数据");					
					return result;
				}
				
				//删除本角色所有菜单绑定 好下面重新绑定角色
				roleMenuMapper.deleteRoleMenuByRoleId(model.getRoleId());
						
				if(null!=model.getMenuId1s()){
					for(Integer menuId:model.getMenuId1s()){
						RoleMenu roleMenu=new RoleMenu();
						roleMenu.setRoleId(model.getRoleId());
						roleMenu.setMenuId(menuId);
						roleMenu.setCreateTime(new Date());
						roleMenu.setBtn("");
						roleMenuMapper.insert(roleMenu);
					}
				}
				if(null!=model.getMenuId2s()){
					for(Integer menuId:model.getMenuId2s()){
						RoleMenu roleMenu=new RoleMenu();
						roleMenu.setRoleId(model.getRoleId());
						roleMenu.setMenuId(menuId);
						roleMenu.setCreateTime(new Date());
						roleMenuMapper.insert(roleMenu);
					}
				}
				
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_SUCCESS);
				result.put(Constants.RETURN_MESSAGE_KEY, "success");		
				
				
			}catch(Exception ex){
				ex.printStackTrace();
				result.put(Constants.RETURN_CODE_KEY, Constants.RETURN_CODE_FAIL);
				result.put(Constants.RETURN_MESSAGE_KEY, ex.getMessage());	
			}
			return result;
		}

}
